/*
 * @file storage based on cjj
 */

import fetch from 'isomorphic-fetch'

const NetApi = {
  post(url, body, callback) { // Fetch 请求默认是不带 cookie 的，需要设置 fetch(url, {credentials: 'include'})
    const headers = new Headers()
    headers.append('Content-Type', 'application/json')

    const init = {
      method: 'POST',
      headers,
      body: JSON.stringify(body),
      credentials: 'same-origin', // include:表示可以跨域传递cookie same-origin:表示只能同源传递cookie
      mode: 'cors',
      cache: 'default'
    };
    return fetch(url, init)
      .then(res => res.json())
      .then(j => {
        if (!j.success && j.code === 302) {
          window.location.href = j.data[0]
        } else {
          callback(null, j)
        }
      })
      .catch(err => { callback(err.message) })
  },

  get(url, callback) {
    const headers = new Headers();
    headers.append('Content-Type', 'application/json');

    const init = {
      method: 'GET',
      headers,
      credentials: 'same-origin', // include:表示可以跨域传递cookie same-origin:表示只能同源传递cookie
      mode: 'cors',
      cache: 'default'
    };
    return fetch(url, init)
      .then(res => res.json())
      .then(j => {
        if (!j.success && j.code === 302) {
          window.location.href = j.data[0]
        } else {
          callback(null, j)
        }
      })
      .catch(err => { callback(err.message) })
  },

  buildQueryUrl(url, params) {
    let paramsUrl = url
    if (_.size(params)>0 && paramsUrl) {
      /**
       例如url为: /sample
       传入的参数为: {id:123,typeId:2343}
       /sample?id=123&typeId=2343
       **/
      paramsUrl += '?';
      let first = true;
      _.each(params,(v,k)=>{
        if (v != -1) {
          if(first) {
            paramsUrl += k+'='+v;
            first=false;
          } else {
            paramsUrl += '&'+k+'='+v;
          }
        }
      })
    }
    return paramsUrl
  },
}

export { NetApi }
